;(function($){
	/* private:
	 * 
	 */
	Array.prototype._foreach = function(callback) {
		for(var i = 0; i < this.length; i++) {
			callback(this[i]);
		}
	}
	function toolbar(tools, panel){
		var bar = $('<div/>').attr({'class':'toolbar'}).appendTo(panel);
		for(var i = 0; i<tools.length; i++){
			if (tools[i].label) {
				$('<span/>').text(tools[i].label).appendTo(bar)
			}
			$(tools[i].control).appendTo(bar);
		}
	}
	function _grid(kwargs, panel) {
		var warpper = $('<div/>').attr({'class':'grid-wapper'}).appendTo(panel);
		var table = $('<table/>').attr({'class':'table table-condensed'}).appendTo(warpper);
		var header = $('<thead/>').appendTo(table);
		var tr = $('<tr>').appendTo(header);
		kwargs.header._foreach(function(item) {
			$('<th>').text(item.name).appendTo(tr);
		});
		var body = $('<tbody>').appendTo(table);
		return warpper;
	}
	
	
	/* public:
	 * 
	 */
	$.fn.jxgrid = function(kwarg){
		var panel_style = kwarg.shadow?'panel panel-shadow':'panel';
		var panel = $('<div/>').attr({'class':panel_style}).appendTo(this);
		if (kwarg.toolbar) {
			toolbar(kwarg.toolbar, panel);
		}
		if (kwarg.grid) {
			this.grid = _grid(kwarg.grid, panel);
			this.store= kwarg.grid.store;
		}
		
		return this;
	}
	$.fn.referecne = function(kwarg) {
		var data = kwarg;
		var That = this;
		if (this.grid) {
			$.ajax({
				url:this.store.url,
				type:'POST',
				data:data,
				success:function(response){
					That.grid.find('tbody').html('');
					var data = eval('(' + response + ')');
					data.foreach(function(item){						
						var tr = $('<tr/>').appendTo(That.grid.find('tbody'));
						That.store.fields.foreach(function(field){
							var text = eval("item.{0}".format(field.index));
							$('<td/>').text(text).appendTo(tr);
						})
					});
				}
			});
		} else {
			throw "Must set grid!";
		}
	}
})(jQuery);